<template>
  <div class="upload-container">
    <el-upload
      class="upload-demo"
      :action="uploadUrl"
      :headers="headers"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :on-success="handleSuccess"
      :on-error="handleError"
      :before-upload="beforeUpload"
      :file-list="fileList"
      :multiple="multiple"
      :limit="limit"
      :on-exceed="handleExceed"
      :disabled="disabled"
      :accept="accept"
      list-type="picture-card">
      <i class="el-icon-plus"></i>
      <div slot="tip" class="el-upload__tip">只能上传{{ accept }}文件，且不超过{{ fileSize }}MB</div>
    </el-upload>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'

export default {
  name: 'ResourceUpload',
  props: {
    // 是否多选
    multiple: {
      type: Boolean,
      default: false
    },
    // 上传数量限制
    limit: {
      type: Number,
      default: 5
    },
    // 文件大小限制(MB)
    fileSize: {
      type: Number,
      default: 50
    },
    // 文件类型限制
    accept: {
      type: String,
      default: 'image/*'
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default: false
    },
    // 初始文件列表
    value: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      uploadUrl: process.env.VUE_APP_BASE_API + '/system/pageResource/upload',
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      fileList: []
    }
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          this.fileList = val.map(item => {
            if (typeof item === 'string') {
              return { name: this.getFileName(item), url: item }
            } else {
              return item
            }
          })
        } else {
          this.fileList = []
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    // 获取文件名
    getFileName(url) {
      if (url) {
        return url.substring(url.lastIndexOf('/') + 1)
      }
      return ''
    },
    // 上传前校验
    beforeUpload(file) {
      const isLt = file.size / 1024 / 1024 < this.fileSize
      if (!isLt) {
        this.$message.error(`文件大小不能超过 ${this.fileSize} MB!`)
        return false
      }
      return true
    },
    // 文件上传成功 - 适配七牛云返回格式
    handleSuccess(response, file, fileList) {
      if (response.code === 200) {
        this.$message.success('上传成功')
        this.fileList = fileList
        this.$emit('input', fileList.map(item => {
          if (item.response) {
            // 七牛云返回的数据结构可能不同，需要适配
            return item.response.url
          } else {
            return item.url
          }
        }))
        
        // 构建完整的文件信息对象传递给父组件
        const fileData = {
          url: response.url,
          size: file.size,
          type: file.type || file.raw.type
        }
        this.$emit('success', fileData)
        return true
      } else {
        this.$message.error(response.msg)
        return false
      }
    },
    // 文件上传失败
    handleError(err) {
      this.$message.error('上传失败: ' + err)
    },
    // 文件数量超出限制
    handleExceed() {
      this.$message.warning(`最多只能上传 ${this.limit} 个文件`)
    },
    // 预览
    handlePreview(file) {
      const url = file.url || (file.response && file.response.data.url)
      window.open(url)
    },
    // 移除文件
    handleRemove(file, fileList) {
      this.fileList = fileList
      this.$emit('input', fileList.map(item => {
        if (item.response) {
          return item.response.data.url
        } else {
          return item.url
        }
      }))
      this.$emit('remove', file)
    }
  }
}
</script>

<style scoped>
.upload-container {
  margin-bottom: 20px;
}
</style> 